<template>
        <div class="demo-enter">
            <h4>demo-enter</h4>
            <button @click="godemo(1)">demo1</button>
            <button  @click="godemo(2)">demo2</button>
            <button  @click="deletedemo(1)">delate-demo2</button>
        </div>
</template>
    
<script setup lang='ts'>
    import axios from 'axios';
    import { useRoute, useRouter } from 'vue-router';
    import demo1 from './demo1.vue';
    import demo2 from './demo2.vue';
    let router = useRouter();
    let route = useRoute();
    const compObj = {
        demo1:demo1,
        demo2: demo2
    };

    let deleteObj = {
        demo1: null,
        demo2: null
    };
    let routeData;


   let init = async() => {
       routeData = await axios.get('http://localhost:8888/getrouters');
       console.log('routeData:', routeData.data);
       routeData.data.routes.forEach(item => {
           console.log('动态添加路由=》', item);
           let deleteItem = router.addRoute({
                path: item.path,
                name: item.name,
                component: compObj[item.component]
            });
            let key: keyof typeof deleteObj = item.component;
            deleteObj[key] = deleteItem;
            console.log('deleteObj=》', deleteObj);
       });

    //    router.hasRoute()：检查路由是否存在。
    // router.getRoutes()：获取一个包含所有路由记录的数组。
       console.log('查看路由记录：',router.getRoutes());
   };
    init();



   let godemo = function(type: number) {
       if (router.hasRoute('Demo'+type)) {
           router.push({
                name: 'Demo' + type
            });
       } else {
           alert('Demo'+type+'路由已经被删除！');
       }
   };

   let deletedemo = (type: number) => {
       // 第一种是通过addRoute的返回值函数删除
    //    deleteObj['demo'+type]();

       // 第二种通过添加一个名称冲突的路由。如果添加与现有途径名称相同的途径，会先删除路由，再添加路由：
    //    router.addRoute({
    //        path: '/',
    //        name: 'Demo' + type,
    //        component: demo1
    //    });

    // 第三种通过使用 router.removeRoute() 按名称删除路由：
    router.removeRoute('Demo'+ type);
       alert(`删除Demo${type}成功`);
   };
</script>
    
<style>
    .demo-enter {
        width: 100%;
        height: 300px;
        background-color: blueviolet;
    }
</style>